package com.ljkj.blockpay.widget;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.view.View;

import com.ljkj.blockpay.ui.activity.ReceiptActivity;
import com.luck.picture.lib.tools.ToastUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by yp on 2022/3/7
 */
public class ScreenshotUtil {

    /**
     * 截取指定activity显示内容
     * @param activity
     */
    public static void saveScreenshotFromActivity(Activity activity){
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        Bitmap bitmap = view.getDrawingCache();
        saveImageToGallery(bitmap,activity);
        //回收资源
        view.setDrawingCacheEnabled(false);
        view.destroyDrawingCache();

    }

    /**
     * 截取指定View显示内容
     * @param view
     * @param context
     */
    public static void saveScreenshotFromView(View view, Activity context){
        view.setDrawingCacheEnabled(true);
        Bitmap bitmap = view.getDrawingCache();
        //回收资源
        view.setDrawingCacheEnabled(false);
        view.destroyDrawingCache();

    }

    /**
     * 保存图片到相册
     * @param bitmap
     * @param activity
     */
    public static void saveImageToGallery(Bitmap bitmap, Activity activity) {
        File appDir = new File(getDCIM());
        if (!appDir.exists()){
            appDir.mkdirs();
        }
        String fileName = System.currentTimeMillis()+".jpg";
        File file = new File(appDir,fileName);

        try {
            FileOutputStream fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG,100,fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        ToastUtils.s(activity.getBaseContext(), "图片保存成功");
        activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + getDCIM())));
    }

    /**
     * 获取相册路径
     * @return
     */
    private static String getDCIM() {
        if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
            return "";
        }
        String path = Environment.getExternalStorageDirectory().getPath()+"/dcim/";
        if (new File(path).exists()){
            return path;
        }
        path = Environment.getExternalStorageDirectory().getPath()+"/DCIM/";
        File file = new File(path);
        if (!file.exists()){
            if (!file.mkdirs()){
                return "";
            }
        }
        return path;
    }

}
